package com.sinochem.sales.common.bean;

import com.sinochem.sales.common.entity.Result;
import com.sinochem.sales.common.exception.BusinessException;
import com.thoughtworks.xstream.core.BaseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author xuan😴🐶🐱🐽🌺  <a href="zhangshixuanj@163.com">联系作者</a>
 * @version Revision:v1.0,Date: 2018/4/23 9:08
 * @project parent
 * @description
 * @Modification Date: 2018/4/23 9:08  {填写修改说明}
 */
@RestController
@ControllerAdvice
public class GlobalExceptionHandler {
    private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = RuntimeException.class)
    public Result defaultErrorHandler(Exception e) {
        e.printStackTrace();
        log.error("参数非法异常={}", e.getMessage(), e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(value = BusinessException.class)
    public Result BusinessException(BusinessException e) {
        e.printStackTrace();
        log.error("参数非法异常={}", e.getMessage(), e);
        return e.getResult();
    }


    @ExceptionHandler(value = BaseException.class)
    public Result BusinessException(BaseException e) {
        e.printStackTrace();
        log.error("参数非法异常={}", e.getMessage(), e);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(MultipartException.class)
    public Result handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
        e.printStackTrace();
        log.error("参数非法异常={}", e.getMessage(), e);
        return Result.error(e.getMessage());
    }

    /**
     * 系统异常处理，比如：404,500
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result defaultErrorHandler(HttpServletRequest req, Exception e) {
        if (e instanceof NoHandlerFoundException) {
            return Result.error("404", e.getMessage());
        } else {
            return Result.error("500", e.getMessage());
        }
    }
}
